﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using ipi.MCC.Controls;

namespace ipi.MCC.CustomFieldTypes
{
    [Guid("1b607421-e5c0-499a-b385-e0d3ea9ac027")]
    public class MCCTreePositionFieldControl : BaseChoiceField
    {
        protected MCCTreeControl tcMain;
        private string sStartNodeID;
        
        public MCCTreePositionFieldControl()
            : base()
        { }

        protected override string DefaultTemplateName
        {
            get
            {
                return "MCCTreePositionFieldControl";
            }
        }
               
        public override object Value
        {
            get
            {
                EnsureChildControls();
                SPFieldMultiChoiceValue mcvTreePosition = new SPFieldMultiChoiceValue();
                System.Collections.Specialized.StringCollection sccSelected = tcMain.CheckedNodes();
                foreach (string sSelected in sccSelected)
                {
                    mcvTreePosition.Add(sSelected);
                }

                return mcvTreePosition;                

            }

            set
            {
                EnsureChildControls();
                SPFieldMultiChoiceValue mcvTreePosition = (SPFieldMultiChoiceValue)value;
                for (int iIndex = 0; iIndex < mcvTreePosition.Count; iIndex++)
                {
                    tcMain.SetToCheckNodeID(Convert.ToInt32(mcvTreePosition[iIndex]));
                }
            }
        }

        public void SetStartNodeID(string NodeID)
        {
            sStartNodeID = NodeID;
        }
        
        protected override void CreateChildControls()
        {
            if (Field == null) return;
            base.CreateChildControls();

            if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)
                return;

            tcMain = (MCCTreeControl)TemplateContainer.FindControl("tcMain");
            if (tcMain == null)
                throw new ArgumentException("tcMain is null. Corrupted MCCTreePositionFieldControl.ascx file.");

            if (!Page.IsPostBack)
            {
                tcMain.Checkable = true;
                tcMain.RootNode = "Root";
                tcMain.StartNodeID = sStartNodeID;
            }
        }
    }
}
